<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="isDefault">
        <el-tag :class="row.isDefault ? 'successTag' : 'dangerTag'">{{ row.isDefault ? '是' : '否' }}</el-tag>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="samplingStandardSearch">
        <el-select
          name="samplingStandard"
          placeholder="请选择 抽样标准类型"
          :clearable="true"
          v-model="search.samplingStandard"
          @change="seachChangeSamplingStandard(search.samplingStandard)"
        >
          <el-option v-for="item in samplingStandardList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
        </el-select>
      </template>
      <template slot-scope="{ row }" slot="severityCodeSearch">
        <el-select name="severityCode" placeholder="请选择 严格程度" :clearable="true" :disabled="severityCodeDisabled" v-model="search.severityCode">
          <el-option v-for="item in severityCodeList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
        </el-select>
      </template>
      <template slot-scope="{ row }" slot="inspectionLevelTypeSearch">
        <el-select name="inspectionLevelType" placeholder="请选择 检验水平" :clearable="true" :disabled="inspectionLevelTypeDisabled" v-model="search.inspectionLevelType">
          <el-option v-for="item in inspectionLevelTypeList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
        </el-select>
      </template>
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.aql_delete" @click="handleDelete">删 除 </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getDict } from '@/api/warehouse/aql';
import { mapGetters } from 'vuex';
export default {
  components: {},
  data() {
    return {
      pageCode: 'AQL',
      form: {},
      query: {},
      loading: true,
      tableOption: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {},
      severityCodeDisabled: false,
      inspectionLevelTypeDisabled: false,
      selectionList: [],
      samplingStandardList: [],
      severityCodeList: [],
      inspectionLevelTypeList: [],
      option: {
        height: 'calc(100vh - 420px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 24,
        border: true,
        index: true,
        menu: true,
        editBtn: true,
        indexLabel: '序号',
        viewBtn: true,
        viewTitle: '详情',
        viewBtnText: '详情',
        selection: true,
        delBtn: false,
        labelWidth: 140,
        searchLabelWidth: 110,
        searchMenuPosition: 'right',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '抽样标准类型',
            prop: 'samplingStandard',
            search: true,
            type: 'select',
            formsolt: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=sample_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入抽样标准类型',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              if (val === 'MIL-STD-1916 C-0') {
                return {
                  severityCode: {
                    display: false
                  },
                  inspectionLevelType: {
                    display: false
                  },
                  inspectionLevelCode: {
                    display: false
                  }
                };
              } else if (val === 'GB/2828') {
                return {
                  severityCode: {
                    display: true
                  },
                  inspectionLevelType: {
                    display: true
                  },
                  inspectionLevelCode: {
                    display: true
                  }
                };
              }
            }
          },
          {
            label: 'AQL抽样名称',
            prop: 'name'
          },
          {
            label: '严格程度',
            prop: 'severityCode',
            type: 'select',
            search: true,
            formsolt: true,
            display: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=sample_plan',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入严格程度',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '下限数量',
            prop: 'batchFrom',
            type: 'number',
            controls: false,
            rules: [
              {
                required: true,
                message: '请输入下限数量',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^\+?[1-9]\d*$/;
                  if (String(value).length > 10) {
                    callback(new Error('最大位数不能超过10位'));
                  } else if (!reg.test(value)) {
                    callback(new Error('只能输入正整数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '上限数量',
            prop: 'batchTo',
            type: 'number',
            controls: false,
            rules: [
              {
                required: true,
                message: '请输入上限数量',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^\+?[1-9]\d*$/;
                  if (String(value).length > 10) {
                    callback(new Error('最大位数不能超过10位'));
                  } else if (!reg.test(value)) {
                    callback(new Error('只能输入正整数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '检验水平',
            prop: 'inspectionLevelType',
            type: 'select',
            search: true,
            formsolt: true,
            display: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=aql_inspection_level',
            cascader: ['inspectionLevelCode'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            control: (val, form) => {
              if (val == 'SPECIAL') {
                return {
                  inspectionLevelCode: { dicUrl: '/api/blade-system/dict/dictionary?code=special_inspection_level' }
                };
              } else {
                return {
                  inspectionLevelCode: { dicUrl: '/api/blade-system/dict/dictionary?code=general_inspection_level' }
                };
              }
            },
            rules: [
              {
                required: true,
                message: '请输入检验水平',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验水平代码',
            prop: 'inspectionLevelCode',
            type: 'select',
            cascader: ['sampleSizeCode'],
            display: true,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicData: [
              {
                dictValue: 'Ⅰ',
                dictKey: '1'
              },
              {
                dictValue: 'Ⅱ',
                dictKey: '2'
              },
              {
                dictValue: 'Ⅲ',
                dictKey: '3'
              }
            ],
            control: (val, form) => {
              switch (val) {
                case 'S-1':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        return res.data.slice(0, 4);
                      }
                    }
                  };
                case 'S-2':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        return res.data.slice(0, 5);
                      }
                    }
                  };
                case 'S-3':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        return res.data.slice(0, 8);
                      }
                    }
                  };
                case 'S-4':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        return res.data.slice(0, 10);
                      }
                    }
                  };
                case '1':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        return res.data.slice(0, 13);
                      }
                    }
                  };
                case '2':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        return res.data.slice(0, 15);
                      }
                    }
                  };
                case '3':
                  return {
                    sampleSizeCode: {
                      dicFormatter: (res) => {
                        console.log(res.data.slice(1, 15));
                        return res.data.slice(1, 16);
                      }
                    }
                  };
                default:
                  break;
              }
            },
            rules: [
              {
                required: true,
                message: '请输入检验水平代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '数字代码',
            prop: 'sampleSizeCode',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_code',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入数字代码',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.aql_add, false),
        viewBtn: this.vaildData(this.permission.aql_view, false),
        delBtn: this.vaildData(this.permission.aql_delete, false),
        editBtn: this.vaildData(this.permission.aql_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.getSampleTypeRequst();
    this.getSeverityCodeRequst();
    this.getInspectionLevelTypeRequst();
  },
  methods: {
    rowSave(row, done, loading) {
      if (Number(row.batchTo) < Number(row.batchFrom)) {
        this.$message({
          type: 'warning',
          message: '上限数量需大于下限数量'
        });
        loading();
        return;
      }
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      if (Number(row.batchTo) < Number(row.batchFrom)) {
        this.$message({
          type: 'warning',
          message: '上限数量需大于下限数量'
        });
        loading();
        return;
      }
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.search = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      // if (params.numberCode) {
      //   params.sampleSizeCode = params.numberCode;
      //   delete params.numberCode;
      // }
      if (this.search.samplingStandard) {
        params.samplingStandard = this.search.samplingStandard;
      }
      if (this.search.severityCode) {
        params.severityCode = this.search.severityCode;
      }
      if (this.search.inspectionLevelType) {
        params.inspectionLevelType = this.search.inspectionLevelType;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async getSampleTypeRequst() {
      try {
        const res = await getDict({
          code: 'sample_type'
        });
        this.samplingStandardList = res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    async getSeverityCodeRequst() {
      try {
        const res = await getDict({
          code: 'sample_plan'
        });
        this.severityCodeList = res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    async getInspectionLevelTypeRequst() {
      try {
        const res = await getDict({
          code: 'aql_inspection_level'
        });
        this.inspectionLevelTypeList = res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },

    seachChangeSamplingStandard(val) {
      if (val === 'GB/2828') {
        this.inspectionLevelTypeDisabled = false;
        this.severityCodeDisabled = false;
      } else {
        this.inspectionLevelTypeDisabled = true;
        this.severityCodeDisabled = true;
        this.search.inspectionLevelType = '';
        this.search.severityCode = '';
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
